package com.uuah.server.transport.provider.mina;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;

import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.uuah.server.api.transport.provider.mina.IServerAcceptorFactory;
import com.uuah.utils.StringUtils;

/**
 *
 * TODO comment ...
 *
 * <p>
 * update record:updator，update time，update content and version
 * </p>
 *
 * @author <a href="jonny_quan@hotmail.com">jonny</a>
 * @date 2009 2009-3-27 下午02:46:43
 * @version 1.0.0
 */
public class MinaServerAcceptorFactory implements IServerAcceptorFactory {

	public SocketAcceptor createServerAcceptor(URI uri) throws IOException {
		String host = StringUtils.defaultIfEmpty(uri.getHost(), "localhost");
		InetAddress inetAddress = InetAddress.getByName(host);

		if (inetAddress.equals(InetAddress.getLocalHost())
				|| inetAddress.isLoopbackAddress()
				|| host.trim().equals("localhost")) {
			return createServerAcceptor(uri.getPort());
		} else {
			return createServerAcceptor(inetAddress, uri.getPort());
		}
	}

	public SocketAcceptor createServerAcceptor(InetAddress address, int port)
			throws IOException {
		return configure(new NioSocketAcceptor(Runtime.getRuntime()
				.availableProcessors() + 1), new InetSocketAddress(address,
				port));
	}

	public SocketAcceptor createServerAcceptor(int port) throws IOException {
		return configure(new NioSocketAcceptor(Runtime.getRuntime()
				.availableProcessors() + 1), new InetSocketAddress(port));
	}

	protected SocketAcceptor configure(SocketAcceptor acceptor,
			InetSocketAddress address) throws IOException {
		acceptor.setDefaultLocalAddress(address);
		return acceptor;
	}
}
